package MTT::Controller::Monitor;
use Moose;
use namespace::autoclean;

BEGIN {extends 'Catalyst::Controller'; }

=head1 NAME

MTT::Controller::Monitor - Catalyst Controller

=head1 DESCRIPTION

Catalyst Controller.

=head1 METHODS

=cut


=head2 index

=cut
use Data::Dumper;

use Class::Date qw(now);
use HTML::Table;

sub index :Path :Args(0) {
    my ( $self, $c ) = @_;

	$c->stash->{template} = 'log.tt2';

	my ($start_time, $end_time);

	my $select = 'SELECT level, date, login, type, ip, message FROM user_log';

	if ( $c->req->method eq 'POST' ) {
		$start_time = $c->req->params->{user_start_time};
		$end_time 	= $c->req->params->{user_end_time};
	}
	unless ( $start_time ) {
		$start_time = now - '30m';
		$start_time = $start_time->strftime('%Y-%m-%d %H:%M:%S');
	}
	$c->stash->{user_start_time} = $start_time; 

	my @levels = ('T', 'D', 'I', 'W', 'E', 'F');
	my $user_level = $c->req->params->{user_level} || 'I';
	
	my $l = 0;
	my @ulvs;
	unless ( $c->req->params->{user_level_only} ) {
		$l++ while $l < @levels && $levels[$l] ne $user_level;
		@ulvs = @levels[$l..$#levels];
	}
	else {
		@ulvs = ( $c->req->params->{user_level} );
	}
	
	$select .= " WHERE date >= '$start_time'";
	$select .= " AND date <= '$end_time'" if $end_time;
	$select .= ' AND level IN (' . join(', ', map {"'$_'"} @ulvs) . ')' unless $user_level eq 'T'; 

	$select .= " AND login = '" . $c->req->params->{user_users} . "'" if $c->req->params->{user_users}; 

	$select .= " AND type = '" . $c->req->params->{user_category} . "'" if $c->req->params->{user_category};

	$select .= ' ORDER BY date DESC';

	my $user_log = $c->model('DBIC')->schema->storage->dbh_do(
		sub {
			my ($storage, $dbh) = @_;
			return $dbh->selectall_arrayref($select);
		}
	);

	my @users = $c->model('DBIC::User')->all();
	$c->stash->{users} = \@users;

	my @categories = $c->model('DBIC::UserLog')->search({}, {columns => ['type'], distinct => 1});
	$c->stash->{user_categories} = \@categories;

	$c->stash->{user_log} = $user_log;
}


=head1 AUTHOR

A clever guy

=head1 LICENSE

This library is free software. You can redistribute it and/or modify
it under the same terms as Perl itself.

=cut

__PACKAGE__->meta->make_immutable;

1;
